# -*- coding: utf-8 -*-
"""
创建/更新 WMS 的桌面工作区入口（Workspace）
- 顶级入口，名称: wms（URL: /app/wms），标题/标签：仓储管理，图标：getting-started
- app 归属：wms（不修改第三方代码，仅在站点层面创建 Workspace 数据）
- 尝试添加常用 DocType 快捷入口（若目标版本 Workspace 支持 links 子表）

用法：
bench --site dev.local execute eam.test.create_wms_workspace.run
"""
import frappe

WORKSPACE_NAME = "wms"
WORKSPACE_LABEL = "仓储管理"
WORKSPACE_TITLE = "仓储管理"
WORKSPACE_ICON = "getting-started"
WORKSPACE_APP = "wms"

LINK_DOCTYPES = [
    ("Storage Bin", "货位"),
    ("Storage Bin Type", "货位类型"),
    ("Storage Bin Qty", "货位库存"),
    ("Warehouse Task", "上下架任务"),
    ("Warehouse Task Detail", "上下架任务明细"),
]

# 额外的常用 DocType 快捷方式（显示在工作区卡片区）
SHORTCUT_DOCTYPES = [
    ("Warehouse", "仓库"),
    ("Stock Entry", "库存交易"),
    ("Purchase Receipt", "采购收货"),
    ("Delivery Note", "送货单"),
    ("Stock Reconciliation", "库存调整"),
    ("Item", "物料"),
    ("Batch", "批号"),
    ("Storage Bin", "货位"),
    ("Storage Bin Type", "货位类型"),
    ("Storage Bin Qty", "货位库存"),
    ("Warehouse Task", "上下架任务"),
]

def _ensure_links(ws):
    """根据当前 Frappe 版本能力，尽量添加 DocType 快捷入口"""
    try:
        if not ws.meta.has_field("links"):
            return
        # 清理已有 links，避免重复
        if getattr(ws, "links", None):
            ws.set("links", [])
        for doctype, label in LINK_DOCTYPES:
            if frappe.db.exists("DocType", doctype):
                ws.append("links", {
                    "type": "Link",
                    "link_type": "DocType",
                    "label": label,
                    "link_to": doctype
                })
    except Exception:
        # 低版本或字段不兼容则忽略
        pass

def _ensure_shortcuts(ws):
    """尽量添加常用 DocType 的快捷卡片"""
    try:
        if not ws.meta.has_field("shortcuts"):
            return
        # 清理已有 shortcuts，避免重复
        if getattr(ws, "shortcuts", None):
            ws.set("shortcuts", [])
        for doctype, label in SHORTCUT_DOCTYPES:
            if frappe.db.exists("DocType", doctype):
                ws.append("shortcuts", {
                    "type": "Link",
                    "link_type": "DocType",
                    "label": label,
                    "link_to": doctype
                })
    except Exception:
        # 低版本或字段不兼容则忽略
        pass

def run():
    # 获取或新建 Workspace
    if frappe.db.exists("Workspace", WORKSPACE_NAME):
        ws = frappe.get_doc("Workspace", WORKSPACE_NAME)
    else:
        ws = frappe.new_doc("Workspace")
        ws.name = WORKSPACE_NAME

    # 设置基本属性（顶级）
    ws.app = WORKSPACE_APP
    ws.label = WORKSPACE_LABEL
    ws.title = WORKSPACE_TITLE
    ws.icon = WORKSPACE_ICON
    ws.parent_page = ""  # 顶级

    # 兼容可选字段
    if ws.meta.has_field("public"):
        ws.public = 1
    if ws.meta.has_field("is_default"):
        ws.is_default = 0
    if ws.meta.has_field("module"):
        # 不强绑 ERPNext 模块，避免校验失败
        ws.module = None

    _ensure_links(ws)
    _ensure_shortcuts(ws)

    # 保存
    if ws.is_new():
        ws.insert(ignore_permissions=True)
    else:
        ws.save(ignore_permissions=True)

    frappe.db.commit()
    print("workspace_wms_ready")